<template>
  <div class="sms-billing-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">消息账单</h2>
        <el-tag type="success" effect="plain" class="version-tag">企业版</el-tag>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-download" @click="handleExportBill">
          导出账单
        </el-button>
        <el-button icon="el-icon-refresh" @click="handleRefresh" :loading="loading">刷新</el-button>
        <!-- 开发环境下的测试按钮 -->
        <el-button v-if="isDev" type="warning" icon="el-icon-connection" @click="testApiConnection" size="small">
          测试API
        </el-button>
      </div>
    </div>

    <!-- 信息提示条 -->
    <el-alert
      title="消息账单按月结算，每月1日生成上月账单。如需变更结算周期或开具发票，请联系客户经理。"
      type="info"
      show-icon
      :closable="false"
      class="info-alert"
    />

    <!-- 账单周期选择 -->
    <el-card class="period-selector-card" shadow="hover" v-loading="loading" element-loading-text="加载账单数据中...">
      <div class="period-selector">
        <div class="selector-label">
          <i class="el-icon-date"></i>
          <span>账单周期：</span>
        </div>
        <el-date-picker
          v-model="billingPeriod"
          type="month"
          placeholder="选择账单月份"
          format="yyyy年MM月"
          value-format="yyyy-MM"
          @change="handlePeriodChange"
          :disabled="loading"
        />
      </div>
    </el-card>

    <!-- 统计卡片区域 -->
    <el-row :gutter="20" class="stat-cards" v-loading="loading">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon">
              <i class="el-icon-message"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">本期消息发送量</div>
              <div class="stat-value">{{ formatNumber(stats.totalSent) }}</div>
              <div class="stat-trend" :class="stats.sentTrend > 0 ? 'up' : 'down'">
                <i :class="stats.sentTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                <span>{{ Math.abs(stats.sentTrend) }}%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon blue">
              <i class="el-icon-money"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">本期账单金额</div>
              <div class="stat-value">¥ {{ formatNumber(stats.totalAmount.toFixed(2)) }}</div>
              <div class="stat-trend" :class="stats.amountTrend > 0 ? 'up' : 'down'">
                <i :class="stats.amountTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                <span>{{ Math.abs(stats.amountTrend) }}%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon green">
              <i class="el-icon-s-claim"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">成功发送率</div>
              <div class="stat-value">{{ stats.successRate }}%</div>
              <div class="stat-trend" :class="stats.successRateTrend > 0 ? 'up' : 'down'">
                <i :class="stats.successRateTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                <span>{{ Math.abs(stats.successRateTrend) }}%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon orange">
              <i class="el-icon-price-tag"></i>
            </div>
            <div class="stat-info">
              <div class="stat-label">平均单价</div>
              <div class="stat-value">¥ {{ stats.averagePrice.toFixed(3) }}</div>
              <div class="stat-trend" :class="stats.priceTrend > 0 ? 'up' : 'down'">
                <i :class="stats.priceTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                <span>{{ Math.abs(stats.priceTrend) }}%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 消息类型分布图表 -->
    <el-row :gutter="20" class="chart-row" v-loading="loading">
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <i class="el-icon-pie-chart"></i>
              <span>消息类型分布</span>
            </div>
          </div>
          <div class="chart-container" ref="typeChart"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <i class="el-icon-data-line"></i>
              <span>消息发送趋势</span>
            </div>
          </div>
          <div class="chart-container" ref="trendChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 账单明细 -->
    <el-card class="bill-details-card" shadow="hover" v-loading="loading">
      <div slot="header" class="card-header">
        <div class="header-title">
          <i class="el-icon-document"></i>
          <span>账单明细</span>
        </div>
        <div class="header-actions">
          <el-radio-group v-model="detailType" size="small" @change="handleDetailTypeChange">
            <el-radio-button label="daily">日账单</el-radio-button>
            <el-radio-button label="type">按类型</el-radio-button>
            <el-radio-button label="app">按应用</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="left-section">
          <el-select v-model="filterType" placeholder="消息类型" size="small" style="width: 120px" @change="handleFilterChange">
            <el-option label="全部类型" value="all"></el-option>
            <el-option label="验证码" value="verification"></el-option>
            <el-option label="通知" value="notification"></el-option>
            <el-option label="营销" value="marketing"></el-option>
          </el-select>

          <el-select v-if="detailType === 'app'" v-model="filterApp" placeholder="应用" size="small" style="width: 150px; margin-left: 10px" @change="handleFilterChange">
            <el-option label="全部应用" value="all"></el-option>
            <el-option v-for="app in appList" :key="app.id" :label="app.name" :value="app.id"></el-option>
          </el-select>
        </div>
        <div class="right-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索"
            prefix-icon="el-icon-search"
            clearable
            size="small"
            style="width: 200px"
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          />
        </div>
      </div>

      <!-- 日账单表格 -->
      <el-table
        v-if="detailType === 'daily'"
        :data="filteredDailyBills"
        style="width: 100%"
        :header-cell-style="tableHeaderStyle"
        border
        stripe
      >
        <el-table-column label="日期" prop="date" width="120" align="center"></el-table-column>
        <el-table-column label="发送量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.sentCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.successCount) }}
          </template>
        </el-table-column>
        <el-table-column label="失败量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.failCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="120" align="center">
          <template slot-scope="{ row }">
            {{ ((row.successCount / row.sentCount) * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="计费条数" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.billedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="金额(元)" width="120" align="right">
          <template slot-scope="{ row }">
            {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 按类型账单表格 -->
      <el-table
        v-if="detailType === 'type'"
        :data="filteredTypeBills"
        style="width: 100%"
        :header-cell-style="tableHeaderStyle"
        border
        stripe
      >
        <el-table-column label="消息类型" prop="typeName" width="120" align="center">
          <template slot-scope="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">{{ row.typeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.sentCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.successCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="120" align="center">
          <template slot-scope="{ row }">
            {{ ((row.successCount / row.sentCount) * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="单价(元/条)" width="120" align="center">
          <template slot-scope="{ row }">
            {{ row.unitPrice.toFixed(3) }}
          </template>
        </el-table-column>
        <el-table-column label="计费条数" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.billedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="金额(元)" width="120" align="right">
          <template slot-scope="{ row }">
            {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="占比" min-width="180">
          <template slot-scope="{ row }">
            <div class="percentage-bar">
              <el-progress
                :percentage="row.percentage"
                :color="getTypeColor(row.type)"
                :show-text="false"
              ></el-progress>
              <span class="percentage-text">{{ row.percentage.toFixed(2) }}%</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 按应用账单表格 -->
      <el-table
        v-if="detailType === 'app'"
        :data="filteredAppBills"
        style="width: 100%"
        :header-cell-style="tableHeaderStyle"
        border
        stripe
      >
        <el-table-column label="应用名称" prop="appName" min-width="150" align="left"></el-table-column>
        <el-table-column label="应用ID" prop="appId" width="180" align="center"></el-table-column>
        <el-table-column label="发送量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.sentCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功量" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.successCount) }}
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="120" align="center">
          <template slot-scope="{ row }">
            {{ ((row.successCount / row.sentCount) * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="计费条数" width="120" align="center">
          <template slot-scope="{ row }">
            {{ formatNumber(row.billedCount) }}
          </template>
        </el-table-column>
        <el-table-column label="金额(元)" width="120" align="right">
          <template slot-scope="{ row }">
            {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="handleViewAppDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 开发环境调试信息 -->
    <el-card v-if="isDev" class="debug-card" shadow="hover">
      <div slot="header" class="debug-header">
        <span>调试信息</span>
        <el-button type="text" @click="debugVisible = !debugVisible">
          {{ debugVisible ? '隐藏' : '显示' }}
        </el-button>
      </div>
      <div v-show="debugVisible" class="debug-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <h4>API状态</h4>
            <p>用户ID: {{ $store.state.user.userId || '未登录' }}</p>
            <p>账单周期: {{ billingPeriod }}</p>
            <p>加载状态: {{ loading ? '加载中' : '完成' }}</p>
            <p>时间范围: {{ getMonthDateRange(billingPeriod).startDate }} 至 {{ getMonthDateRange(billingPeriod).endDate }}</p>
          </el-col>
          <el-col :span="6">
            <h4>统计数据</h4>
            <p>总发送量: {{ stats.totalSent }}</p>
            <p>成功率: {{ stats.successRate }}%</p>
            <p>总金额: ¥{{ stats.totalAmount.toFixed(2) }}</p>
            <p>平均单价: ¥{{ stats.averagePrice.toFixed(3) }}</p>
          </el-col>
          <el-col :span="6">
            <h4>数据条数</h4>
            <p>日账单: {{ dailyBills.length }}条</p>
            <p>类型账单: {{ typeBills.length }}条</p>
            <p>应用账单: {{ appBills.length }}条</p>
            <p>图表数据: {{ chartData.typeDistribution.length }}类型</p>
          </el-col>
          <el-col :span="6">
            <h4>价格配置</h4>
            <p>通知: ¥{{ priceInfo.smsNoticePrice.toFixed(3) }}</p>
            <p>营销: ¥{{ priceInfo.smsSellPrice.toFixed(3) }}</p>
            <p>图文: ¥{{ priceInfo.smsPicturePrice.toFixed(3) }}</p>
            <p>语音: ¥{{ priceInfo.smsVoicePrice.toFixed(3) }}</p>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      title="消息发送详情"
      :visible.sync="detailDialogVisible"
      width="800px"
    >
      <div v-if="selectedDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日期">{{ selectedDetail.date }}</el-descriptions-item>
          <el-descriptions-item label="发送总量">{{ formatNumber(selectedDetail.sentCount) }}</el-descriptions-item>
          <el-descriptions-item label="成功数量">{{ formatNumber(selectedDetail.successCount) }}</el-descriptions-item>
          <el-descriptions-item label="失败数量">{{ formatNumber(selectedDetail.failCount) }}</el-descriptions-item>
          <el-descriptions-item label="成功率">{{ ((selectedDetail.successCount / selectedDetail.sentCount) * 100).toFixed(2) }}%</el-descriptions-item>
          <el-descriptions-item label="计费条数">{{ formatNumber(selectedDetail.billedCount) }}</el-descriptions-item>
          <el-descriptions-item label="金额">¥ {{ selectedDetail.amount.toFixed(2) }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <div class="section-title">类型分布</div>
          <el-table :data="selectedDetail.typeBreakdown" border style="width: 100%">
            <el-table-column label="消息类型" prop="typeName" width="120" align="center">
              <template slot-scope="{ row }">
                <el-tag :type="getTypeTagType(row.type)" size="small">{{ row.typeName }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="发送量" prop="count" width="120" align="center"></el-table-column>
            <el-table-column label="成功量" prop="successCount" width="120" align="center"></el-table-column>
            <el-table-column label="成功率" width="120" align="center">
              <template slot-scope="{ row }">
                {{ ((row.successCount / row.count) * 100).toFixed(2) }}%
              </template>
            </el-table-column>
            <el-table-column label="金额(元)" prop="amount" width="120" align="right">
              <template slot-scope="{ row }">
                {{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="占比" min-width="180">
              <template slot-scope="{ row }">
                <div class="percentage-bar">
                  <el-progress
                    :percentage="row.percentage"
                    :color="getTypeColor(row.type)"
                    :show-text="false"
                  ></el-progress>
                  <span class="percentage-text">{{ row.percentage.toFixed(2) }}%</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleExportDetail">导出详情</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listSmsRecord, Listfsl, Listfslfl, Listkhjg, getPriceByUserId, listSmsCount } from "@/api/Sms/SmsRecord"
import { listChannels } from "@/api/Sms/channels"

export default {
  name: 'SmsBilling',
  data() {
    return {
      // 加载状态
      loading: false,
      
      // 账单周期
      billingPeriod: this.getCurrentMonth(),

      // 统计数据
      stats: {
        totalSent: 0,
        sentTrend: 0,
        totalAmount: 0,
        amountTrend: 0,
        successRate: 0,
        successRateTrend: 0,
        averagePrice: 0,
        priceTrend: 0
      },

      // 图表实例
      typeChart: null,
      trendChart: null,

      // 明细类型
      detailType: 'daily',

      // 筛选条件
      filterType: 'all',
      filterApp: 'all',
      searchQuery: '',

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 详情对话框
      detailDialogVisible: false,
      selectedDetail: null,

      // 应用列表
      appList: [
        { id: 'app-001', name: '用户中心' },
        { id: 'app-002', name: '订单系统' },
        { id: 'app-003', name: '支付系统' },
        { id: 'app-004', name: '营销平台' }
      ],

      // 通道列表
      channelsList: [],

      // 价格信息
      priceInfo: {
        smsNoticePrice: 0.030,
        smsSellPrice: 0.035,
        smsPicturePrice: 0.040,
        smsVoicePrice: 0.050,
        smsSmartPrice: 0.060
      },

      // 真实数据
      dailyBills: [],
      typeBills: [],
      appBills: [],
      
      // 图表数据
      chartData: {
        typeDistribution: [],
        trendData: []
      },

      // 开发环境调试
      debugVisible: false
    }
  },
  computed: {
    // 表格样式
    tableHeaderStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        fontWeight: 500,
        height: '50px'
      }
    },

    // 开发环境判断
    isDev() {
      return process.env.NODE_ENV === 'development'
    },

    // 过滤后的日账单
    filteredDailyBills() {
      let result = [...this.dailyBills]

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(bill =>
          bill.date.toLowerCase().includes(query)
        )
      }

      // 类型过滤
      if (this.filterType !== 'all') {
        result = result.filter(bill => {
          // 检查类型明细中是否有匹配的类型
          const typeDetail = bill.typeBreakdown.find(t => t.type === this.filterType)
          return typeDetail && typeDetail.count > 0
        })
      }

      return result
    },

    // 过滤后的类型账单
    filteredTypeBills() {
      let result = [...this.typeBills]

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(bill =>
          bill.typeName.toLowerCase().includes(query)
        )
      }

      // 类型过滤
      if (this.filterType !== 'all') {
        result = result.filter(bill => bill.type === this.filterType)
      }

      return result
    },

    // 过滤后的应用账单
    filteredAppBills() {
      let result = [...this.appBills]

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(bill =>
          bill.appName.toLowerCase().includes(query) ||
          bill.appId.toLowerCase().includes(query)
        )
      }

      // 应用过滤
      if (this.filterApp !== 'all') {
        result = result.filter(bill => bill.appId === this.filterApp)
      }

      return result
    }
  },
  async created() {
    try {
      this.loading = true;
      await this.initializeData();
    } catch (error) {
      console.error('初始化失败:', error);
      this.$message.error('数据加载失败，请刷新重试');
    } finally {
      this.loading = false;
    }
  },
  methods: {
    /** 初始化数据 */
    async initializeData() {
      try {
        // 并行获取基础数据
        await Promise.all([
          this.getPriceInfo(),
          this.getChannelsList(),
          this.loadBillingData()
        ]);
      } catch (error) {
        console.error('初始化数据失败:', error);
        throw error;
      }
    },

    /** 获取价格信息 */
    async getPriceInfo() {
      try {
        const userId = this.$store.state.user.userId;
        if (!userId) {
          console.warn('用户ID不存在，使用默认价格');
          return;
        }

        const response = await getPriceByUserId(userId);
        console.log('价格信息响应:', response);
        
        if (response && response.code === 200 && response.data) {
          this.priceInfo = {
            smsNoticePrice: parseFloat(response.data.smsNoticePrice || 0.030),
            smsSellPrice: parseFloat(response.data.smsSellPrice || 0.035),
            smsPicturePrice: parseFloat(response.data.smsPicturePrice || 0.040),
            smsVoicePrice: parseFloat(response.data.smsVoicePrice || 0.050),
            smsSmartPrice: parseFloat(response.data.smsSmartPrice || 0.060)
          };
          console.log('价格信息已更新:', this.priceInfo);
        } else {
          console.warn('价格信息响应格式异常，使用默认价格:', response);
        }
      } catch (error) {
        console.error('获取价格信息失败:', error);
        this.$message.warning('获取价格信息失败，使用默认价格');
        // 使用默认价格
      }
    },

    /** 获取通道列表 */
    async getChannelsList() {
      try {
        const response = await listChannels();
        console.log('通道列表响应:', response);
        
        if (response && response.code === 200 && Array.isArray(response.rows)) {
          this.channelsList = response.rows;
        } else if (response && Array.isArray(response.data)) {
          this.channelsList = response.data;
        } else if (Array.isArray(response)) {
          this.channelsList = response;
        } else {
          console.warn('通道列表响应格式异常:', response);
          this.channelsList = [];
        }
        
        console.log('通道列表已更新:', this.channelsList.length, '个通道');
      } catch (error) {
        console.error('获取通道列表失败:', error);
        this.$message.warning('获取通道列表失败');
        this.channelsList = [];
      }
    },

    /** 获取当前月份 */
    getCurrentMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      return `${year}-${month}`;
    },

    /** 获取月份的开始和结束日期 */
    getMonthDateRange(period) {
      const [year, month] = period.split('-');
      const startDate = `${year}-${month}-01`;
      const endDate = new Date(year, month, 0).getDate();
      const endDateStr = `${year}-${month}-${endDate.toString().padStart(2, '0')}`;
      return { startDate, endDate: endDateStr };
    },

    /** 验证API参数 */
    validateApiParams(params) {
      const requiredFields = ['userId'];
      const missingFields = requiredFields.filter(field => !params[field]);
      
      if (missingFields.length > 0) {
        console.error('缺少必要参数:', missingFields);
        this.$message.error(`缺少必要参数: ${missingFields.join(', ')}`);
        return false;
      }
      
      // 验证时间参数
      if (params.startTime && params.endTime) {
        const startDate = new Date(params.startTime);
        const endDate = new Date(params.endTime);
        
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          console.error('时间参数格式错误:', params.startTime, params.endTime);
          this.$message.error('时间参数格式错误');
          return false;
        }
        
        if (startDate > endDate) {
          console.error('开始时间不能大于结束时间');
          this.$message.error('开始时间不能大于结束时间');
          return false;
        }
      }
      
      return true;
    },

    /** 加载账单数据 */
    async loadBillingData() {
      try {
        const userId = this.$store.state.user.userId;
        
        if (!userId) {
          console.error('用户未登录或用户ID不存在');
          this.$message.error('请先登录');
          return;
        }
        
        const { startDate, endDate } = this.getMonthDateRange(this.billingPeriod);
        
        // 基础查询参数
        const baseParams = {
          userId,
          startTime: startDate,
          endTime: endDate,
          pageSize: 1000
        };

        console.log('基础查询参数:', baseParams);
        
        // 验证参数
        if (!this.validateApiParams(baseParams)) {
          return;
        }

        // 并行获取各种统计数据
        const [
          totalStats,
          successStats,
          typeStats,
          dailyStats
        ] = await Promise.all([
          this.getTotalStats(baseParams),
          this.getSuccessStats(baseParams),
          this.getTypeStats(baseParams),
          this.getDailyStats(baseParams)
        ]);

        console.log('所有API调用完成，开始处理数据...');

        // 处理统计数据
        this.processStatsData(totalStats, successStats);
        
        // 处理类型数据
        this.processTypeData(typeStats);
        
        // 处理日账单数据
        this.processDailyData(dailyStats);
        
        // 更新图表
        this.$nextTick(() => {
          this.initCharts();
        });

        console.log('账单数据加载完成');

      } catch (error) {
        console.error('加载账单数据失败:', error);
        this.$message.error('加载账单数据失败，请重试');
        throw error;
      }
    },

    /** 获取总发送统计 */
    async getTotalStats(params) {
      try {
        console.log('调用总发送统计API，参数:', params);
        
        const response = await listSmsCount(params);
        console.log('总发送统计API响应:', response);
        
        // 验证响应数据
        if (response === null || response === undefined) {
          console.error('总发送统计API返回null或undefined');
          return 0;
        }
        
        if (response && response.code === 200) {
          return parseInt(response.data) || 0;
        } else if (response && response.total !== undefined) {
          return parseInt(response.total) || 0;
        } else if (response && response.code && response.code !== 200) {
          console.error('总发送统计API返回错误代码:', response.code, '错误信息:', response.msg);
          this.$message.error(`获取总发送统计失败: ${response.msg || '未知错误'}`);
          return 0;
        } else {
          console.warn('获取总发送统计响应格式异常:', response);
          return 0;
        }
      } catch (error) {
        console.error('获取总发送统计失败:', error);
        if (error.response) {
          this.$message.error(`获取总发送统计失败: ${error.response.status} - ${error.response.data?.msg || '服务器错误'}`);
        } else {
          this.$message.error(`获取总发送统计失败: ${error.message}`);
        }
        return 0;
      }
    },

    /** 获取成功发送统计 */
    async getSuccessStats(params) {
      try {
        console.log('调用成功发送统计API，参数:', params);
        
        const successParams = { ...params, smsStatus: '0' }; // 0表示成功
        const response = await listSmsCount(successParams);
        console.log('成功发送统计API响应:', response);
        
        // 验证响应数据
        if (response === null || response === undefined) {
          console.error('成功发送统计API返回null或undefined');
          return 0;
        }
        
        if (response && response.code === 200) {
          return parseInt(response.data) || 0;
        } else if (response && response.total !== undefined) {
          return parseInt(response.total) || 0;
        } else if (response && response.code && response.code !== 200) {
          console.error('成功发送统计API返回错误代码:', response.code, '错误信息:', response.msg);
          this.$message.error(`获取成功发送统计失败: ${response.msg || '未知错误'}`);
          return 0;
        } else {
          console.warn('获取成功发送统计响应格式异常:', response);
          return 0;
        }
      } catch (error) {
        console.error('获取成功发送统计失败:', error);
        if (error.response) {
          this.$message.error(`获取成功发送统计失败: ${error.response.status} - ${error.response.data?.msg || '服务器错误'}`);
        } else {
          this.$message.error(`获取成功发送统计失败: ${error.message}`);
        }
        return 0;
      }
    },

    /** 获取类型统计 */
    async getTypeStats(params) {
      try {
        console.log('调用类型统计API，参数:', params);
        
        const response = await Listfslfl(params);
        console.log('类型统计API响应:', response);
        
        // 验证响应数据
        if (response === null || response === undefined) {
          console.error('类型统计API返回null或undefined');
          return [];
        }
        
        if (response && response.code === 200 && Array.isArray(response.rows)) {
          console.log('类型统计数据解析成功, 数据条数:', response.rows.length);
          return response.rows;
        } else if (response && Array.isArray(response.data)) {
          console.log('类型统计数据解析成功(data格式), 数据条数:', response.data.length);
          return response.data;
        } else if (Array.isArray(response)) {
          console.log('类型统计数据解析成功(数组格式), 数据条数:', response.length);
          return response;
        } else if (response && response.code && response.code !== 200) {
          console.error('类型统计API返回错误代码:', response.code, '错误信息:', response.msg);
          this.$message.error(`获取类型统计失败: ${response.msg || '未知错误'}`);
          return [];
        } else {
          console.warn('获取类型统计响应格式异常:', response);
          return [];
        }
      } catch (error) {
        console.error('获取类型统计失败:', error);
        if (error.response) {
          this.$message.error(`获取类型统计失败: ${error.response.status} - ${error.response.data?.msg || '服务器错误'}`);
        } else {
          this.$message.error(`获取类型统计失败: ${error.message}`);
        }
        return [];
      }
    },

    /** 获取日统计 */
    async getDailyStats(params) {
      try {
        console.log('调用日统计API，参数:', params);
        
        // 检查必要参数
        if (!params.userId) {
          console.error('缺少userId参数');
          return [];
        }
        
        // 根据smsstatistcs.vue的正确格式设置参数
        const startDate = new Date(params.startTime);
        const endDate = new Date(params.endTime);
        const dayNumber = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
        
        const formattedParams = {
          userId: params.userId,
          other2: params.endTime,    // 结束时间
          other3: dayNumber,         // 天数差
          other5: params.startTime,  // 开始时间
          smsStatus: null            // 获取全部状态
        };
        
        console.log('Listfsl API格式化参数:', formattedParams);
        console.log(`时间范围: ${params.startTime} 到 ${params.endTime}, 共 ${dayNumber} 天`);
        
        const response = await Listfsl(formattedParams);
        console.log('日统计API响应:', response);
        
        // 验证响应数据
        if (response === null || response === undefined) {
          console.error('日统计API返回null或undefined');
          this.$message.warning('无法获取日统计数据，将使用模拟数据展示');
          return this.generateMockDailyData();
        }
        
        if (response && response.code === 200 && Array.isArray(response.rows)) {
          console.log('日统计数据解析成功, 数据条数:', response.rows.length);
          return response.rows;
        } else if (response && Array.isArray(response.data)) {
          console.log('日统计数据解析成功(data格式), 数据条数:', response.data.length);
          return response.data;
        } else if (Array.isArray(response)) {
          console.log('日统计数据解析成功(数组格式), 数据条数:', response.length);
          return response;
        } else if (response && response.code && response.code !== 200) {
          console.error('日统计API返回错误代码:', response.code, '错误信息:', response.msg);
          this.$message.error(`获取日统计失败: ${response.msg || '未知错误'}`);
          return this.generateMockDailyData();
        } else {
          console.warn('日统计响应格式异常:', response);
          return this.generateMockDailyData();
        }
      } catch (error) {
        console.error('获取日统计失败:', error);
        
        // 更详细的错误信息
        if (error.response) {
          console.error('响应状态:', error.response.status);
          console.error('响应数据:', error.response.data);
          this.$message.error(`获取日统计失败: ${error.response.status} - ${error.response.data?.msg || '服务器错误'}`);
        } else if (error.request) {
          console.error('请求发送失败:', error.request);
          this.$message.error('获取日统计失败: 网络连接异常');
        } else {
          console.error('错误信息:', error.message);
          this.$message.error(`获取日统计失败: ${error.message}`);
        }
        
        // 返回模拟数据作为降级方案
        return this.generateMockDailyData();
      }
    },

    /** 生成模拟的日统计数据 */
    generateMockDailyData() {
      console.log('生成模拟日统计数据');
      
      const { startDate, endDate } = this.getMonthDateRange(this.billingPeriod);
      const start = new Date(startDate);
      const end = new Date(endDate);
      
      const mockData = [];
      
      // 生成该月每一天的模拟数据
      for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
        const dateStr = d.toISOString().split('T')[0];
        
        // 模拟一些随机但合理的数据
        const baseCount = Math.floor(Math.random() * 1000) + 500;
        
        mockData.push({
          other1: baseCount.toString(), // 发送数量
          other2: dateStr // 日期
        });
      }
      
      console.log('生成了', mockData.length, '天的模拟数据');
      return mockData;
    },

    /** 处理统计数据 */
    processStatsData(totalCount, successCount) {
      this.stats.totalSent = totalCount;
      const successRate = totalCount > 0 ? ((successCount / totalCount) * 100).toFixed(1) : 0;
      this.stats.successRate = parseFloat(successRate);
      
      // 计算总金额（基于成功发送的消息）
      this.stats.totalAmount = successCount * this.priceInfo.smsNoticePrice;
      
      // 计算平均单价
      this.stats.averagePrice = this.priceInfo.smsNoticePrice;
      
      // 趋势数据暂时设为0，需要对比上月数据
      this.stats.sentTrend = 0;
      this.stats.amountTrend = 0;
      this.stats.successRateTrend = 0;
      this.stats.priceTrend = 0;

      console.log('统计数据处理完成:', {
        totalSent: this.stats.totalSent,
        successRate: this.stats.successRate,
        totalAmount: this.stats.totalAmount
      });
    },

    /** 处理类型数据 */
    processTypeData(typeData) {
      console.log('开始处理类型数据:', typeData);
      
      this.typeBills = [];
      this.chartData.typeDistribution = [];
      
      if (!Array.isArray(typeData) || typeData.length === 0) {
        console.warn('类型数据为空或格式错误');
        return;
      }
      
      let totalAmount = 0;
      let totalCount = 0;

      typeData.forEach(item => {
        // 数据验证
        if (!item || !item.other1) {
          console.warn('跳过无效的类型数据项:', item);
          return;
        }

        const count = parseInt(item.other1) || 0;
        const type = item.other2 || '';
        
        if (count === 0) {
          console.warn('跳过数量为0的类型数据项:', item);
          return;
        }
        
        let typeName = '';
        let unitPrice = 0;
        let typeKey = '';
        let color = '';

        switch (type) {
          case '1':
            typeName = '验证码';
            typeKey = 'verification';
            unitPrice = this.priceInfo.smsNoticePrice;
            color = '#409EFF';
            break;
          case '2':
            typeName = '通知';
            typeKey = 'notification';
            unitPrice = this.priceInfo.smsNoticePrice;
            color = '#67C23A';
            break;
          case '3':
            typeName = '营销';
            typeKey = 'marketing';
            unitPrice = this.priceInfo.smsSellPrice;
            color = '#E6A23C';
            break;
          case '4':
            typeName = '图文';
            typeKey = 'multimedia';
            unitPrice = this.priceInfo.smsPicturePrice;
            color = '#F56C6C';
            break;
          default:
            typeName = '其他';
            typeKey = 'other';
            unitPrice = this.priceInfo.smsNoticePrice;
            color = '#909399';
        }

        const amount = count * unitPrice;
        totalAmount += amount;
        totalCount += count;

        this.typeBills.push({
          type: typeKey,
          typeName,
          sentCount: count,
          successCount: count, // 假设成功率100%，实际应该从API获取
          billedCount: count,
          unitPrice,
          amount,
          percentage: 0 // 稍后计算
        });

        this.chartData.typeDistribution.push({
          name: typeName,
          value: count,
          itemStyle: { color }
        });
      });

      // 计算百分比
      this.typeBills.forEach(bill => {
        bill.percentage = totalCount > 0 ? ((bill.sentCount / totalCount) * 100) : 0;
      });

      console.log('类型数据处理完成:', {
        typeBills: this.typeBills.length,
        typeDistribution: this.chartData.typeDistribution.length,
        totalCount,
        totalAmount
      });
    },

    /** 处理日账单数据 */
    processDailyData(dailyData) {
      console.log('开始处理日账单数据:', dailyData);
      
      this.dailyBills = [];
      this.chartData.trendData = {
        dates: [],
        sentCounts: [],
        successCounts: []
      };

      if (!Array.isArray(dailyData) || dailyData.length === 0) {
        console.warn('日账单数据为空或格式错误');
        return;
      }

      dailyData.forEach(item => {
        // 数据验证
        if (!item || !item.other1 || !item.other2) {
          console.warn('跳过无效的日账单数据项:', item);
          return;
        }

        const date = item.other2; // 日期
        const count = parseInt(item.other1) || 0; // 发送数量
        
        if (count === 0) {
          console.warn('跳过数量为0的日账单数据项:', item);
          return;
        }
        
        // 假设成功率95%，实际应该从API获取详细数据
        const successCount = Math.floor(count * 0.95);
        const failCount = count - successCount;
        const amount = successCount * this.priceInfo.smsNoticePrice;

        this.dailyBills.push({
          date,
          sentCount: count,
          successCount,
          failCount,
          billedCount: successCount,
          amount,
          typeBreakdown: [] // 需要额外API获取详细分类
        });

        // 图表数据
        this.chartData.trendData.dates.push(this.parseTime(date, '{m}-{d}'));
        this.chartData.trendData.sentCounts.push(count);
        this.chartData.trendData.successCounts.push(successCount);
      });

      console.log('日账单数据处理完成:', {
        dailyBills: this.dailyBills.length,
        trendData: this.chartData.trendData.dates.length
      });
    },

    /** 时间格式化 */
    parseTime(time, pattern) {
      if (!time) return '';
      
      const date = new Date(time);
      const format = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };

      return pattern.replace(/{([ymdhis])+}/g, (result, key) => {
        const value = format[key];
        return value.toString().padStart(2, '0');
      });
    },

    // 格式化数字
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },

    // 获取类型标签样式
    getTypeTagType(type) {
      const types = {
        'verification': 'primary',
        'notification': 'success',
        'marketing': 'warning',
        'multimedia': 'danger'
      }
      return types[type] || ''
    },

    // 获取类型颜色
    getTypeColor(type) {
      const colors = {
        'verification': '#409EFF',
        'notification': '#67C23A',
        'marketing': '#E6A23C',
        'multimedia': '#F56C6C'
      }
      return colors[type] || '#909399'
    },

    // 初始化图表
    initCharts() {
      if (!this.$refs.typeChart || !this.$refs.trendChart) {
        return;
      }

      // 初始化消息类型分布图表
      this.typeChart = echarts.init(this.$refs.typeChart)
      this.typeChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.chartData.typeDistribution.map(item => item.name)
        },
        series: [
          {
            name: '消息类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.chartData.typeDistribution
          }
        ]
      })

      // 初始化消息发送趋势图表
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.trendChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['发送量', '成功量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartData.trendData.dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '发送量',
            type: 'line',
            data: this.chartData.trendData.sentCounts,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '成功量',
            type: 'line',
            data: this.chartData.trendData.successCounts,
            smooth: true,
            lineStyle: {
              width: 3,
              color: '#67C23A'
            },
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      })
    },

    // 账单周期变更
    async handlePeriodChange(val) {
      this.billingPeriod = val;
      console.log('账单周期变更:', val);
      
      try {
        this.loading = true;
        await this.loadBillingData();
      this.$message({
        message: `已切换至 ${val} 账单`,
        type: 'success'
        });
      } catch (error) {
        this.$message.error('切换账单周期失败');
      } finally {
        this.loading = false;
      }
    },

    // 明细类型变更
    handleDetailTypeChange(val) {
      console.log('明细类型变更:', val)
      this.currentPage = 1
    },

    // 筛选变更
    handleFilterChange() {
      this.currentPage = 1
      // 实现筛选逻辑
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      // 实现搜索逻辑
    },

    // 导出账单
    handleExportBill() {
      this.$message({
        message: '账单导出中，请稍候...',
        type: 'info'
      })

      setTimeout(() => {
        this.$message({
          message: '账单导出成功',
          type: 'success'
        })
      }, 1500)
    },

    // 刷新
    async handleRefresh() {
      try {
        this.loading = true;
        await this.loadBillingData();
      this.$message({
        message: '数据已刷新',
        type: 'success'
        });
      } catch (error) {
        this.$message.error('刷新失败');
      } finally {
        this.loading = false;
      }
    },

    // 查看详情
    handleViewDetail(row) {
      this.selectedDetail = row
      this.detailDialogVisible = true
    },

    // 查看应用详情
    handleViewAppDetail(row) {
      this.$message({
        message: `查看应用 ${row.appName} 的详情`,
        type: 'info'
      })
    },

    // 导出详情
    handleExportDetail() {
      this.$message({
        message: '详情导出中，请稍候...',
        type: 'info'
      })

      setTimeout(() => {
        this.$message({
          message: '详情导出成功',
          type: 'success'
        })
        this.detailDialogVisible = false
      }, 1500)
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      // 实现分页逻辑
    },
    handleCurrentChange(val) {
      this.currentPage = val
      // 实现分页逻辑
    },

    // 窗口大小变化时重绘图表
    resizeCharts() {
      this.typeChart?.resize()
      this.trendChart?.resize()
    },

    /** 测试API连接 */
    async testApiConnection() {
      console.log('=== 开始API连接测试 ===');
      
      try {
        const userId = this.$store.state.user.userId;
        console.log('当前用户ID:', userId);
        
        if (!userId) {
          this.$message.error('用户未登录，无法测试API');
          return;
        }
        
        // 测试基础参数
        const testParams = {
          userId,
          pageSize: 10,
          pageNum: 1
        };
        
        console.log('测试参数:', testParams);
        
        // 逐个测试API
        const apiTests = [
          { name: 'listSmsRecord', fn: () => listSmsRecord(testParams) },
          { name: 'listSmsCount', fn: () => listSmsCount(testParams) },
          { name: 'Listfslfl', fn: () => Listfslfl(testParams) }
        ];
        
        let successCount = 0;
        const results = [];
        
        for (const test of apiTests) {
          console.log(`\n--- 测试 ${test.name} ---`);
          try {
            const startTime = Date.now();
            const result = await test.fn();
            const endTime = Date.now();
            
            console.log(`${test.name} 响应时间: ${endTime - startTime}ms`);
            console.log(`${test.name} 响应数据:`, result);
            
            if (result !== null && result !== undefined) {
              successCount++;
              results.push({ name: test.name, status: 'success', data: result, time: endTime - startTime });
              console.log(`${test.name} 测试成功 ✓`);
            } else {
              results.push({ name: test.name, status: 'null', error: 'API返回null', time: endTime - startTime });
              console.log(`${test.name} 测试失败: 返回null ✗`);
            }
          } catch (error) {
            console.error(`${test.name} 测试失败:`, error);
            results.push({ name: test.name, status: 'error', error: error.message });
          }
        }
        
        // 专门测试Listfsl API的不同参数组合
        console.log(`\n--- 专门测试 Listfsl (问题API) ---`);
        const listfslResults = [];
        
        // 计算正确的时间参数
        const { startDate, endDate } = this.getMonthDateRange(this.billingPeriod);
        const start = new Date(startDate);
        const end = new Date(endDate);
        const dayNumber = Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
        
        const listfslParamVariations = [
          { 
            name: 'Listfsl-正确格式', 
            params: { 
              userId, 
              other2: endDate,    // 结束时间
              other3: dayNumber,  // 天数差  
              other5: startDate,  // 开始时间
              smsStatus: null     // 获取全部状态
            } 
          },
          { 
            name: 'Listfsl-简化格式', 
            params: { 
              userId, 
              other2: endDate, 
              other5: startDate 
            } 
          },
          { 
            name: 'Listfsl-只用户ID', 
            params: { userId } 
          }
        ];
        
        for (const variation of listfslParamVariations) {
          console.log(`测试 ${variation.name}，参数:`, variation.params);
          try {
            const startTime = Date.now();
            const result = await Listfsl(variation.params);
            const endTime = Date.now();
            
            console.log(`${variation.name} 响应时间: ${endTime - startTime}ms`);
            console.log(`${variation.name} 响应:`, result);
            
            if (result !== null && result !== undefined) {
              listfslResults.push({ name: variation.name, status: 'success', time: endTime - startTime });
              console.log(`${variation.name} 测试成功 ✓`);
              break; // 找到一个成功的参数组合就停止
            } else {
              listfslResults.push({ name: variation.name, status: 'null', time: endTime - startTime });
              console.log(`${variation.name} 测试失败: 返回null ✗`);
            }
          } catch (error) {
            console.error(`${variation.name} 测试失败:`, error);
            listfslResults.push({ name: variation.name, status: 'error', error: error.message });
          }
        }
        
        // 如果所有Listfsl测试都失败，但至少有一个成功，则总体算部分成功
        const listfslSuccess = listfslResults.some(r => r.status === 'success');
        if (listfslSuccess) {
          successCount++;
          results.push({ name: 'Listfsl', status: 'success', note: '某个参数组合成功' });
        } else {
          results.push({ name: 'Listfsl', status: 'failed', error: '所有参数组合都失败' });
        }
        
        console.log('\n=== API测试结果汇总 ===');
        results.forEach(result => {
          console.log(`${result.name}: ${result.status} ${result.time ? `(${result.time}ms)` : ''} ${result.error ? `- ${result.error}` : ''}`);
        });
        
        console.log(`API测试完成: ${successCount}/4 个接口成功`);
        
        if (successCount === 0) {
          this.$message.error('所有API接口测试失败，请检查网络连接和权限');
        } else if (successCount < 4) {
          this.$message.warning(`部分API接口测试失败 (${successCount}/4)`);
        } else {
          this.$message.success('所有API接口测试成功');
        }
        
        // 如果有失败的API，提供更多信息
        const failedApis = results.filter(r => r.status !== 'success');
        if (failedApis.length > 0) {
          console.log('\n=== 失败的API详情 ===');
          failedApis.forEach(api => {
            console.log(`${api.name}: ${api.error || '未知错误'}`);
          });
        }
        
      } catch (error) {
        console.error('API连接测试失败:', error);
        this.$message.error('API连接测试失败');
      }
      
      console.log('=== API连接测试结束 ===\n');
    },
  },
  mounted() {
    // 监听窗口大小变化，重绘图表
    window.addEventListener('resize', this.resizeCharts)

      // 计算总数
    this.$nextTick(() => {
      if (this.detailType === 'daily') {
        this.total = this.filteredDailyBills.length
      } else if (this.detailType === 'type') {
        this.total = this.filteredTypeBills.length
      } else {
        this.total = this.filteredAppBills.length
      }
    });
  },
  beforeDestroy() {
    // 销毁图表实例
    this.typeChart?.dispose()
    this.trendChart?.dispose()

    // 移除事件监听
    window.removeEventListener('resize', this.resizeCharts)
  },
  watch: {
    // 监听明细类型变化，更新总数
    detailType() {
      if (this.detailType === 'daily') {
        this.total = this.filteredDailyBills.length
      } else if (this.detailType === 'type') {
        this.total = this.filteredTypeBills.length
      } else {
        this.total = this.filteredAppBills.length
      }
    },
    // 监听筛选条件变化，更新总数
    filterType() {
      if (this.detailType === 'daily') {
        this.total = this.filteredDailyBills.length
      } else if (this.detailType === 'type') {
        this.total = this.filteredTypeBills.length
      }
    },
    filterApp() {
      if (this.detailType === 'app') {
        this.total = this.filteredAppBills.length
      }
    },
    searchQuery() {
      if (this.detailType === 'daily') {
        this.total = this.filteredDailyBills.length
      } else if (this.detailType === 'type') {
        this.total = this.filteredTypeBills.length
      } else {
        this.total = this.filteredAppBills.length
      }
    }
  }
}
</script>

<style scoped>
.sms-billing-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  font-size: 22px;
  color: #303133;
  margin: 0;
}

.version-tag {
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  padding: 0 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 信息提示条样式 */
.info-alert {
  margin-bottom: 20px;
}

/* 账单周期选择器样式 */
.period-selector-card {
  margin-bottom: 20px;
}

.period-selector {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selector-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  margin-bottom: 20px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background-color: #ecf5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-icon i {
  font-size: 28px;
  color: #409eff;
}

.stat-icon.blue {
  background-color: #ecf5ff;
}

.stat-icon.blue i {
  color: #409eff;
}

.stat-icon.green {
  background-color: #f0f9eb;
}

.stat-icon.green i {
  color: #67c23a;
}

.stat-icon.orange {
  background-color: #fdf6ec;
}

.stat-icon.orange i {
  color: #e6a23c;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-trend.up {
  color: #f56c6c;
}

.stat-trend.down {
  color: #67c23a;
}

.trend-label {
  color: #909399;
  margin-left: 4px;
}

/* 图表样式 */
.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 360px;
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-title i {
  font-size: 18px;
  color: #409eff;
}

.chart-container {
  height: 300px;
}

/* 账单明细卡片样式 */
.bill-details-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-title i {
  font-size: 18px;
  color: #409eff;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-section {
  display: flex;
  align-items: center;
}

/* 百分比条样式 */
.percentage-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.percentage-text {
  font-size: 13px;
  color: #606266;
  min-width: 50px;
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

/* 调试卡片样式 */
.debug-card {
  margin-bottom: 20px;
  border: 2px dashed #e6a23c;
}

.debug-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  color: #e6a23c;
}

.debug-content {
  font-size: 13px;
}

.debug-content h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.debug-content p {
  margin: 5px 0;
  color: #606266;
}

/* 详情对话框样式 */
.detail-section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

/* 响应式样式 */
@media screen and (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .period-selector {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

@media screen and (max-width: 768px) {
  .sms-billing-container {
    padding: 10px;
  }

  .toolbar {
    flex-direction: column;
    gap: 16px;
  }

  .left-section,
  .right-section {
    width: 100%;
  }

  .right-section .el-input {
    width: 100% !important;
  }

  .header-actions {
    flex-direction: column;
  }

  .header-actions .el-button {
    width: 100%;
  }

  .header-actions .el-radio-group {
    width: 100%;
  }

  .header-actions .el-radio-button {
    width: 33.33%;
  }

  .header-actions .el-radio-button__inner {
    width: 100%;
  }
}
</style>
